package zhizhemodi.tech.short_term_bwork.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import zhizhemodi.tech.short_term_bwork.entity.DirFile;
import zhizhemodi.tech.short_term_bwork.service.DirFileService;
import zhizhemodi.tech.short_term_bwork.tool.CommonResult;

@Controller
@ResponseBody
@RequestMapping("file")
public class FileSystem {
    
    private static String BASE_PATH = "src//main//resources//localStorage";

    @Resource
    DirFileService dirFileService;

    /**
     * 查找文件
     * @param keyWord
     * @param dirUrl
     * @param type
     * @param dId
     * @return
     */
    @GetMapping("list")
    public CommonResult<?> fileList(
        @RequestParam(required = false, name = "keyword") String keyWord,
        @RequestParam(required = false, name = "dirUrl") String dirUrl,
        @RequestParam(required = false, name = "type", defaultValue = "-1") Integer type,
        @RequestParam("departmentId") Integer dId
    ) {
        List<DirFile> fileList = null;
        try {
            fileList = dirFileService.getFileList(keyWord, dirUrl, type, dId);
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success(fileList);
    }

    /**
     * 创建文件夹
     * @param dirFile
     * @return
     */
    @PostMapping("mkdir")
    public CommonResult<?> mkDir(
        @RequestBody DirFile dirFile
    ) {
        try {
            dirFileService.addFile(dirFile);
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success("创建目录成功");
    }

    /**
     * 文件上传接口
     * @param upload 文件组
     * @param request 请求体
     * @param imgUrl 图片路径
     * @param dId 机构编码
     * @param type 文件类型
     * @return 成功返回200，失败返回400
     * @throws IOException
     */
    @PostMapping("upload")
    public CommonResult<?> uploadImg(
        MultipartFile[] upload, 
        HttpServletRequest request, 
        @RequestParam("imgUrl") String imgUrl,
        @RequestParam("departmentId") Integer dId,
        @RequestParam("type") Integer type
    ) throws IOException {
        // 获取项目根路径
        String property = System.getProperty("user.dir");
        for(int i = 0;i < upload.length; i++) {
            // 考虑用户没有上传文件
            if(upload[i] != null) {
                // 处理文件名 UUID 拼串 =uuid + "." + 扩展名 对文件名定义唯一标识
                // String s = UUID.randomUUID().toString().replace("-", "") + "." + FilenameUtils.getExtension(upload[i].getOriginalFilename());
                String s = upload[i].getOriginalFilename();
                // 调用业务 文件拷贝
                File file = new File(property + "//" + BASE_PATH, s);
                DirFile dirFile = new DirFile(0, dId, s, imgUrl, type, false);
                try{
                    if(!file.exists())
                        dirFileService.addFile(dirFile);
                        FileUtils.copyInputStreamToFile(upload[i].getInputStream(), file);
                } catch(Exception e) {
                    CommonResult.failed(e.getMessage());
                }
            }
        }
        return CommonResult.success("文件上传成功");
    }

    /**
     * 图片下载方法
     * @param imgUrl
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    public void download(@RequestParam("url") String imgUrl, HttpServletResponse response) throws IOException{
        // 获取项目根路径
        System.out.println("hello");
        String property = System.getProperty("user.dir");
        File file = new File(property + "//" + BASE_PATH, imgUrl);
        if(file.exists()){
           response.setContentType(getContentType(file.getName()));
           // 这行会导致文件直接下载
           //response.addHeader("Content-Disposition", "attachment;fileName=" + file.toString());
           byte[] buffer = new byte[1024];
           FileInputStream fis = null;
           BufferedInputStream bis = null;
           OutputStream os = null;
           try{
               fis = new FileInputStream(file);
               bis = new BufferedInputStream(fis);
               os = response.getOutputStream();

               int i = bis.read(buffer);
               while (i != -1) {
                   os.write(buffer, 0, i);
                   i = bis.read(buffer);
               }
           }catch (Exception e) {
                e.printStackTrace();
           }finally {
               os.close();
               bis.close();
               fis.close();
           }
        }
        else {
            response.sendError(404);
        }
    }

    /**
     * 删除文件接口
     * @param url
     * @return
     */
    @DeleteMapping("delete")
    public CommonResult<?> delete(@RequestParam("url") String url) {
        // 获取项目根路径
        try {
            dirFileService.deleteFile(url);
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success("删除成功");
    }

    /**
     * 用于返回不同后缀文件使用的contentType内容
     * 通过endsWith方法判断
     * @param fileName
     * @return
     */
    private String getContentType(String fileName) {
        if(fileName.endsWith(".png")) return "image/png";
        else if(fileName.endsWith(".gif")) return "image/gif";
        else if(fileName.endsWith(".jpg")||fileName.endsWith(".jpeg")||fileName.endsWith(".jfif")) return "image/jpeg";
        else if(fileName.endsWith(".bmp")) return "application/x-bmp";
        else if(fileName.endsWith(".mp3")) return "audio/mp3";
        else if(fileName.endsWith(".mp4")) return "video/mpeg4";
        else if(fileName.endsWith(".mov")) return "video/quicktime";
        else if(fileName.endsWith(".txt")) return "text/plain";
        else if(fileName.endsWith(".html") || fileName.endsWith(".htm")) return "text/HTML";
        else return null;
    }
}
